{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0",
   "metadata": {},
   "outputs": [],
   "source": [
    "import math"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1",
   "metadata": {},
   "outputs": [],
   "source": [
    "def decrypt_message(key: int, message: str) -> str:\n",
    "    \"\"\"\n",
    "    列置换解密算法\n",
    "    \n",
    "    参数:\n",
    "        key: 解密密钥(原始加密时的列数)\n",
    "        message: 要解密的密文\n",
    "        \n",
    "    返回:\n",
    "        解密后的明文字符串\n",
    "    \"\"\"\n",
    "    # 计算解密表格参数\n",
    "    num_columns = math.ceil(len(message) / key)\n",
    "    num_rows = key\n",
    "    shaded_boxes = (num_columns * num_rows) - len(message)\n",
    "\n",
    "    # 初始化列容器\n",
    "    plaintext_columns: List[str] = [''] * num_columns\n",
    "    column, row = 0, 0\n",
    "\n",
    "    '''解密时逐字符遍历密文，加密算法亦可写成此形式：\n",
    "def encrypt(key: int, message: str) -> str:\n",
    "    ciphertext_column = [\"\"] * key\n",
    "    column = 0\n",
    "    for symbol in message:\n",
    "        ciphertext_column[column] += symbol\n",
    "        column += 1\n",
    "        if column == key:\n",
    "            column = 0\n",
    "    return ''.join(ciphertext_column)\n",
    "    '''\n",
    "    for symbol in message:\n",
    "        plaintext_columns[column] += symbol\n",
    "        column += 1\n",
    "\n",
    "        # 检查是否需要换行\n",
    "        if (column == num_columns) or \\\n",
    "           (column == num_columns - 1 and row >= num_rows - shaded_boxes):\n",
    "            column = 0\n",
    "            row += 1\n",
    "\n",
    "    return ''.join(plaintext_columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
